package be.phl.obstacleapp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Files.FileColumns;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import be.phl.layoutAdapter.ScreeningItemRowAdapter;
import be.phl.model.DBAdapterScreening;

public class ScreeningRoomActivity extends FragmentActivity implements
		ScreeningRoomListFragment.Callbacks {
	/**
	 * TODO: - delete photos - save pictures in a private folder - memory out of
	 * bound exception? investigate further
	 * 
	 * commentaar bij overzicht > foto's bij overzicht ? kleur voor het
	 * geselecteerde item > done!
	 * 
	 * 
	 */

	private int ScreeningId, ScreeningRoomId, selectedListItemPostion = -1;
	private Fragment detailFragment;
	private ScreeningRoomListFragment listFragment;
	private boolean summarySelected = false;

	// variable to keep track wich view is selected for the detailfragment
	private static final String TAG = "ScreeningRoomActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_screening_room);
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);

		// set the sceeningId and screeningroomId
		ScreeningId = getIntent().getIntExtra("ScreeningId", 0);
		ScreeningRoomId = getIntent().getIntExtra("ScreeningRoomId", 0);
		Log.i(TAG, Integer.toString(ScreeningRoomId));

		DBAdapterScreening db = new DBAdapterScreening(this);
		db.open();
		Cursor c = db.getScreeningRoom(ScreeningRoomId);
		c.moveToFirst();
		getActionBar().setTitle(c.getString(1));
		db.close();

		// Create the list fragment and add it to the activity
		// using a fragment transaction.
		Bundle arguments = new Bundle();
		arguments.putInt(ScreeningRoomListFragment.ARG_SCREENINGROOM_ID,
				ScreeningRoomId);

		// set up the listfragment
		listFragment = new ScreeningRoomListFragment();
		listFragment.setArguments(arguments);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.screeningroom_list, listFragment).commit();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_screening_room, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		// create a new screeningactivity

		Intent screeningAct = new Intent(this, ScreeningActivity.class);
		screeningAct.putExtra("ScreeningId", ScreeningId);
		this.startActivity(screeningAct);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.menu_fragment:

			// change the selected detailview
			// 1: single lines
			// 2: rows - collumns
			Log.i(TAG,
					"Selected detailview: "
							+ MainData.getSCREENING_ROOM_DETAIL_VIEW_SELECTED());
			MainData.setSCREENING_ROOM_DETAIL_VIEW_SELECTED(MainData
					.getSCREENING_ROOM_DETAIL_VIEW_SELECTED() % 2 + 1);

			if (selectedListItemPostion >= 0) {
				// create a new detailfragment to the selected position
				createDetailFragmen(listFragment.getITEMS().get(
						selectedListItemPostion).id);
			}
			return true;

		case R.id.menu_item:
			Log.i(TAG, "Item geselecteerd");
			if (selectedListItemPostion >= 0) {
				createCommentFragment(CommentFragment.SCREENING_ITEM,
						listFragment.getITEMS().get(selectedListItemPostion)
								.getId());
			} else {
				// if no item is selected, show a message
				Toast toast = Toast.makeText(this,
						"Selecteer eerst een onderdeel", Toast.LENGTH_LONG);
				toast.show();
			}
			return true;
		case R.id.menu_room:
			Log.i(TAG, "Kamer geselecteerd");
			createCommentFragment(CommentFragment.SCREENING_ROOM,
					ScreeningRoomId);
			return true;
		case R.id.menu_name:

			// rename the screeningroom
			// Use the Builder class for convenient dialog construction
			AlertDialog.Builder builder = new AlertDialog.Builder(this);

			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			input.setText(getActionBar().getTitle());

			builder.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							Log.i(TAG, "Room renamed: " + input.getText());
							DBAdapterScreening db = new DBAdapterScreening(
									ScreeningRoomActivity.this);
							db.open();
							db.updateScreeningRoomName(ScreeningRoomId, input
									.getText().toString());
							db.close();
							ScreeningRoomActivity.this.getActionBar().setTitle(
									input.getText().toString());
						}
					})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// User cancelled the dialog
								}
							}).setTitle("Naam").setView(input).create();
			builder.show();
			return true;
		case R.id.menu_summary:
			// get a summary of all the selected problems
			if (!summarySelected) {
				Bundle arguments = new Bundle();
				arguments.putInt(
						ScreeningProblemSummaryFragment.ARG_SCREENINGROOM_ID,
						ScreeningRoomId);
				detailFragment = new ScreeningProblemSummaryFragment();
				detailFragment.setArguments(arguments);
				getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.screeningroom_detail_container,
								detailFragment).commit();
				summarySelected = true;
			} else {
				if (selectedListItemPostion >= 0) {
					// create a new detailfragment to the selected position
					createDetailFragmen(listFragment.getITEMS().get(
							selectedListItemPostion).id);
				}
				summarySelected = false;
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * create a new dialog to insert comment
	 * 
	 * @param selected
	 * @param id
	 */
	public void createCommentFragment(final int selected, final int id) {
		// create a fragment manager to show the comment fragment
		FragmentManager fm = getSupportFragmentManager();
		final CommentFragment editCommentDialog = new CommentFragment();

		DBAdapterScreening db = new DBAdapterScreening(
				ScreeningRoomActivity.this);
		db.open();
		Cursor c = db.getComment(id, selected);
		c.moveToFirst();
		String content = c.getString(0);
		editCommentDialog.setContent(content == null ? "" : content);
		db.close();

		editCommentDialog.mButtonCallback = new CommentFragment.Callbacks() {

			@Override
			public void onCanceled(String comment) {

				// save the changes to the database
				DBAdapterScreening db = new DBAdapterScreening(
						ScreeningRoomActivity.this);
				db.open();
				db.updateComment(id, selected, comment);
				db.close();

				// close the dialog
				editCommentDialog.dismiss();

			}
		};
		editCommentDialog.show(fm, "fragment_comment");
	}

	/**
	 * Callback method from {@link ScreeningRoomListFragment.Callbacks}
	 * indicating that the item with the given ID was selected.
	 */
	@Override
	public void onItemSelected(int id, int position) {
		// Create the detail fragment and add it to the activity
		// using a fragment transaction.
		selectedListItemPostion = position;
		createDetailFragmen(id);
		summarySelected = false;

	}

	/**
	 * create the detailfragment using the id from the selected item
	 * 
	 * @param id
	 */
	private void createDetailFragmen(int id) {
		Bundle arguments = new Bundle();
		arguments.putInt(ScreeningProblemFragment.ARG_SCREENINGITEM_ID, id);
		switch (MainData.getSCREENING_ROOM_DETAIL_VIEW_SELECTED()) {
		case 1:
			detailFragment = new ScreeningProblemFragment();
			break;
		case 2:
			detailFragment = new TreeViewFragment();
			break;
		}
		detailFragment.setArguments(arguments);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.screeningroom_detail_container, detailFragment)
				.commit();
	}

	/**
	 * Handle returning from camera in the fragment - import the image bitmap
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			// check if we are returning from picture selection
			if (requestCode == ((ScreeningitemGalleryFragment) detailFragment)
					.getPICKER()) {

				// the returned picture URI
				Uri pickedUri = ((ScreeningitemGalleryFragment) detailFragment)
						.getmUriPicTaken();

				// declare the bitmap
				Bitmap pic = null;

				getContentResolver().notifyChange(pickedUri, null);
				ContentResolver cr = getContentResolver();

				// if we have a new URI attempt to decode the image bitmap
				if (pickedUri != null) {

					Log.i(TAG, pickedUri.toString());
					try {
						pic = android.provider.MediaStore.Images.Media
								.getBitmap(cr, pickedUri);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					File newFile;
					try {
						File file = new File(new URI(pickedUri.toString()));
						newFile = new File(this.getFilesDir().getPath(),
								file.getName());
						FileInputStream in = new FileInputStream(file);
						byte[] picture = new byte[(int) file.length()];
						in.read(picture);
						FileOutputStream outputStream = new FileOutputStream(
								newFile);
						outputStream.write(picture);
						in.close();
						outputStream.close();
						file.delete();
						pickedUri = Uri.fromFile(newFile);

					} catch (URISyntaxException e) { // TODO Auto-generated
														// catch block
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					// insert the path from the picture in the database
					DBAdapterScreening db = new DBAdapterScreening(this);
					db.open();
					long id = db.insertPictureItem(
							listFragment.getITEMS()
									.get(selectedListItemPostion).id, pickedUri
									.getPath());
					Log.i(TAG, pickedUri.getPath());
					db.close();

					// pass bitmap to ImageAdapter to add to array
					((ScreeningitemGalleryFragment) detailFragment)
							.getImgAdapt()
							.addPic(new ScreeningitemGalleryFragment.PictureItem(
									Bitmap.createScaledBitmap(pic, 800, 600,
											false), (int) id, pickedUri
											.getPath()));
					// redraw the gallery thumbnails to reflect the new addition
					((ScreeningitemGalleryFragment) detailFragment)
							.getPicGallery()
							.setAdapter(
									((ScreeningitemGalleryFragment) detailFragment)
											.getImgAdapt());

					// display the newly selected image at larger size
					// picView.setImageBitmap(pic);
					((ScreeningitemGalleryFragment) detailFragment)
							.getPicView().setImageBitmap(pic);
					// scale options
					// picView.setScaleType(ImageView.ScaleType.FIT_CENTER);

					/*
					 * ByteArrayOutputStream bos = new ByteArrayOutputStream();
					 * pic.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					 * byte[] bArray = bos.toByteArray();
					 */

				}
			}
		}
		// superclass method
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * handel the event when the photo button is clicked - summary => show
	 * gallery - new photo => start camera app
	 */
	@Override
	public void onButtonClicked(int itemId, int action) {

		// set the detailfragment to show the pictures from the selected
		// screeningitem
		detailFragment = new ScreeningitemGalleryFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.screeningroom_detail_container, detailFragment)
				.commit();

		// get all pictures in the database
		List<ScreeningitemGalleryFragment.PictureItem> pictures = new ArrayList<ScreeningitemGalleryFragment.PictureItem>();
		DBAdapterScreening db = new DBAdapterScreening(this);
		db.open();
		Cursor c = db.getAllPictureItems(itemId);
		int amountPic = c.getCount();
		if (amountPic == 0) {
			if (action == ScreeningItemRowAdapter.GALLERY) {
				// if there's no picture for the selected item show this dialog
				new AlertDialog.Builder(this)
						.setTitle(
								"Geen foto's voor dit onderdeel, wilt u een nieuwe foto maken?")
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// take picture
										takePicture();
									}
								})
						.setNegativeButton(R.string.cancel,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// User cancelled the dialog

									}
								}).show();
			}
		} else {
			while (c.moveToNext()) {
				Log.i(TAG, c.getString(1));
				try {
					// read the file given from the path
					BufferedInputStream buf = new BufferedInputStream(
							new FileInputStream(c.getString(1)));
					pictures.add(new ScreeningitemGalleryFragment.PictureItem(
							Bitmap.createScaledBitmap(
									BitmapFactory.decodeStream(buf), 800, 600,
									false), c.getInt(0), c.getString(1)));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		((ScreeningitemGalleryFragment) detailFragment)
				.setImageBitmaps(new ArrayList<ScreeningitemGalleryFragment.PictureItem>(
						pictures));
		db.close();

		// create fragment to show the pictures from this item
		switch (action) {
		case ScreeningItemRowAdapter.NEW_PHOTO:
			if (amountPic >= 3) {
				Toast toast = Toast.makeText(this,
						"U kunt maximaal 3 foto's maken", Toast.LENGTH_LONG);
				toast.show();
			} else {
				takePicture();
			}
			break;
		case ScreeningItemRowAdapter.GALLERY:

			break;
		}
	}

	/**
	 * use the camera app on the device to capture a picture
	 */
	private void takePicture() {
		// take the user to the built in camera app
		Intent pickIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File pictureFile = ((ScreeningitemGalleryFragment) detailFragment)
				.getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
		pickIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureFile));
		((ScreeningitemGalleryFragment) detailFragment).setmUriPicTaken(Uri
				.fromFile(pictureFile));
		// we will handle the returned data in onActivityResult
		this.startActivityForResult(pickIntent,
				((ScreeningitemGalleryFragment) detailFragment).getPICKER());
	}
}
